package com.stenio.fancat.common;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.stenio.fancat.common.constants.GlobalConstant;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

public class HttpClient {

    private static CloseableHttpClient client = HttpClientBuilder.create().build();

    private Charset defaultCharset = Charset.forName(GlobalConstant.PLATFORM_CHARACTER_ENCODING);

    private Charset charset = defaultCharset;

    public HttpClient() {
    }

    public HttpClient(String charset) {
        this.defaultCharset = Charset.forName(charset);
    }

    public String postJson(String uri, String json) {
        HttpPost post = new HttpPost();
        try {
            post.setURI(new URI(uri));
            post.setHeader("Content-type", "application/json");
            post.setEntity(new StringEntity(json, charset));
            return invoke(post);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String invoke(HttpPost post) throws IOException {
        try (CloseableHttpResponse httpResponse = client.execute(post)) {
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity, Charset.forName(GlobalConstant.PLATFORM_CHARACTER_ENCODING));
        }
    }

    public String postXml(String uri, String xml) {
        HttpPost post = new HttpPost();
        try {
            post.setURI(new URI(uri));
            post.setHeader("Content-type", "application/xml");
            post.setEntity(new StringEntity(xml, charset));
            return invoke(post);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
